/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vng.survey.controller;

import com.vng.zing.survey.thrift.client.SurveyClient;
import com.vng.zing.survey.thrift.model.AnswerItem;
import com.vng.zing.survey.thrift.model.Response;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vng.survey.model.CommonModel;
import com.vng.zing.survey.thrift.model.Error;
import com.vng.zing.survey.thrift.model.QuesType;
import com.vng.zing.survey.thrift.model.State;
import com.vng.zing.survey.thrift.model.SurveyItemResult;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import vng.survey.utility.Utility;


/**
 *
 * @author namhh
 *
 * {"idUser":1,"answers":[{"type":"SINGLE_SELECTION","idQues":"1","answer":"0,0,0,1,"},{"type":"MULTI_CHOICE","idQues":"2","answer":"1,1,1,1,"},{"type":"MULTI_LINE","idQues":"3","answer":"love"}]}
 *
 */
public class AjaxSubmitResponse extends BaseController {

//      protected void processRequest(HttpServletRequest request, HttpServletResponse resp)
//            throws ServletException, IOException, Exception {
////          String myJsonData = request.getParameter("response");
////          String idSurvey = request.getParameter("idSurvey");
////          Response responseItem = (Response) CommonModel.toOBJECT(myJsonData, Response.class);
////          SurveyClient survey = SurveyClient.getInstance();
////          Error error  = survey.newResponse(new Random().nextInt(1000), Integer.parseInt(idSurvey), responseItem);
////          response.setContentType("text/plain");
////          response.setCharacterEncoding("UTF-8");
////          response.getWriter().write(CommonModel.toJSON(error));
//          
//          
//          
//             String error = "";
//        try {
//             
//            int idSurvey = Integer.parseInt(request.getParameter("idSurvey"));
//            String myJsonData = request.getParameter("response");
//            JSONParser parser = new JSONParser();
//            Object obj = parser.parse(myJsonData);
//            JSONObject jsonObject = (JSONObject) obj;
//
//            Long idUser = (Long) jsonObject.get("idUser");
//            
//            ///////////////////////
//            
//            int  a = new Random().nextInt(1000);
//            idUser=new Long(a);
//            
//            /////////////////////////
//            
//            if (idUser== null || idUser<=0) {
//                error += "Invalid ID USER!\n";
//            }
//           
//            SurveyClient survey = SurveyClient.getInstance();
//             if(survey.checkUser(idSurvey, idUser.intValue())!= State.NEW && survey.checkUser(idSurvey, idUser.intValue())!= State.VIEW){
//                resp.setContentType("text/plain");
//                resp.setCharacterEncoding("UTF-8");
//                resp.getWriter().print(CommonModel.toJSON("ERROR", "Bạn không được phép trả lời trang này!"));
//                return;             }
//                 
//            
//            List<AnswerItem> answerItems = new ArrayList<AnswerItem>();
//
//            // loop array
//            JSONArray answers = (JSONArray) jsonObject.get("answers");
//            for (Object object : answers) {
//
//                JSONObject jsonAnswer = (JSONObject) object;
//                short idQues = Short.parseShort((String)jsonAnswer.get("idQues"));
//                if (idQues < 0) {
//                    error += "Mã câu hỏi không hợp lệ!\n";
//                }
//
//
//                String type = (String) jsonAnswer.get("type");
//                if (!type.equals(QuesType.SINGLE_SELECTION.name()) && !type.equals(QuesType.MULTI_CHOICE.name()) && !type.equals(QuesType.MULTI_LINE.name()) && !type.equals(QuesType.SINGLE_LINE.name())) {
//                    error += "Kiểu câu hỏi không hợp lệ!\n";
//                }
//                
//                 String str_require = (String) jsonAnswer.get("require");
//                 boolean require = Boolean.parseBoolean(str_require);
//                
//               
//               String answer = (String) jsonAnswer.get("answer");
//               error+= checkAnswer(type,require,answer);
//               if(!"".equals(error))
//                   break;
//               AnswerItem answerItem = new AnswerItem(QuesType.valueOf(type), idQues, answer,require,(int)(new Date().getTime()/1000));
//               answerItems.add(answerItem);
//            }
//          
//            if("".equals(error)){
//            Response response = new Response(answerItems, idUser.intValue());
//           
//            Error e  = survey.newResponse(idUser.intValue(), idSurvey, response);
//           
//            resp.setContentType("text/plain");
//            resp.setCharacterEncoding("UTF-8");
//             String JSONString = CommonModel.toJSON(e.name(),"");
//            resp.getWriter().print(JSONString);
//            }
//            else{
//             
//                String JSONString = CommonModel.toJSON("Lỗi ", error);
//                resp.setContentType("text/plain");
//                resp.setCharacterEncoding("UTF-8");
//                resp.getWriter().print(JSONString);
//            }
//        } catch (Exception ex) {
//            String JSONString = CommonModel.toJSON("Lỗi ", "Vui lòng thử lại sau!");
//            resp.setContentType("text/plain");
//            resp.setCharacterEncoding("UTF-8");
//            resp.getWriter().print(JSONString);
//        }
//          
//
//    }
    public static String checkAnswer(String type, boolean require, String value) {
        if (!require) {
            return "";
        }
        if (type.equals(QuesType.MULTI_LINE.name()) || type.equals(QuesType.SINGLE_LINE.name())) {
            if (value == null || "".equals(value)) {
                return "Hãy trả lời các câu hỏi bắt buộc!</br>";
            } else {
                return "";
            }
        } else {
            if (type.equals(QuesType.SINGLE_SELECTION.name()) || type.equals(QuesType.MULTI_CHOICE.name())) {
                String[] split = value.split(",");
                for (String string : split) {
                    if ("1".equals(string)) {
                        return "";
                    }
                }
                return "Hãy trả lời các câu hỏi bắt buộc!!</br>";
            }
        }
        return "Hãy trả lời các câu hỏi bắt buộc!</br>";
    }

    @Override
    public String render(HttpServletRequest request, HttpServletResponse resp) throws IOException, Exception {

        String error = "";
        try {
           
            int idSurvey = Integer.parseInt(request.getParameter("idSurvey"));
             SurveyClient survey = SurveyClient.getInstance();
             SurveyItemResult itemResult =survey.getSurvey(idSurvey);
            if(itemResult.getErro()!= Error.SUCCESS || itemResult.getSurveyItem().getIDUser()!=1 ){
             resp.setContentType("text/plain");
                resp.setCharacterEncoding("UTF-8");
                return CommonModel.toJSON("survey khong ton tai", error);
            
            }
            String myJsonData = request.getParameter("response");
            JSONParser parser = new JSONParser();
            Object obj = parser.parse(myJsonData);
            JSONObject jsonObject = (JSONObject) obj;

            Long idUser = (Long) jsonObject.get("idUser");

            ///////////////////////
            int a = new Random().nextInt(10);
            idUser = new Long( new Random().nextInt(10));

            /////////////////////////
            if (idUser == null || idUser <= 0) {
                error += "Tài khoản không hợp lệ!</br>";
            }

           
            if (survey.checkUser(idSurvey, 1) == State.RESPONSE ) {
                return (CommonModel.toJSON("Lỗi", "Bạn đã trả lời khảo sát này này!"));
            }

            List<AnswerItem> answerItems = new ArrayList<AnswerItem>();

            // loop array
            JSONArray answers = (JSONArray) jsonObject.get("answers");
            int time = (int) (new Date().getTime()/1000);
            for (Object object : answers) {

                JSONObject jsonAnswer = (JSONObject) object;
                short idQues = Short.parseShort((String) jsonAnswer.get("idQues"));
                if (idQues < 0) {
                    error += "Mã câu hỏi không hợp lệ!</br>";
                }

                String type = (String) jsonAnswer.get("type");
                if (!type.equals(QuesType.SINGLE_SELECTION.name()) && !type.equals(QuesType.MULTI_CHOICE.name()) && !type.equals(QuesType.MULTI_LINE.name()) && !type.equals(QuesType.SINGLE_LINE.name())) {
                    error += "Kiểu câu hỏi không hợp lệ!</br>";
                }

                String str_require = (String) jsonAnswer.get("require");
                boolean require = Boolean.parseBoolean(str_require);

                String answer = (String) jsonAnswer.get("answer");

                error += checkAnswer(type, require, answer);
                if (!"".equals(error)) {
                    break;
                }
                AnswerItem answerItem = new AnswerItem(QuesType.valueOf(type), idQues, answer, require,time, "ballal");
             
                answerItems.add(answerItem);
            }

            if ("".equals(error)) {
       
                if(!Utility.validResponse(answerItems, itemResult.getSurveyItem().getQuestions())){
                    return CommonModel.toJSON("Lỗi ", error);
                }
         
                Response response = new Response(answerItems,idUser.intValue(), "biakilkdfa");
                System.out.println("respone"+ response);
                Error e = survey.newResponse(1, idSurvey, response);
                return CommonModel.toJSON("Thành công", "Đóng ghóp của bạn đã được nghi nhận!");
            } else {

                return CommonModel.toJSON("Lỗi ", error);
            }
        } catch (Exception ex) {
            return CommonModel.toJSON("Lỗi ", "Vui lòng thử lại sau!");

        }
    }

}
